package com.liuyi.netty.im.test.config.thread;

import com.liuyi.rapid.develop.tool.SpringContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 * 线城池配置
 */
@Configuration
public class TaskPoolConfig {

    @Resource
    private ThreadAsyncProperties properties;

    private static Executor taskExecutor;

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(properties.getCorePoolSize());
        //设置最大线程数
        threadPool.setMaxPoolSize(properties.getMaxPoolSize());
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(properties.getQueueCapacity());
        //线程空闲时间、当多少秒空闲后，并且为队列外的线程将会被回收
        threadPool.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        // 等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown());
        // 等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(properties.getAwaitTerminationMillis());
        //  线程名称前缀
        threadPool.setThreadNamePrefix(properties.getNamePrefix());
        try {
            // 缓冲队列满了之后的拒绝策略：由调用线程处理（一般是主线程）
            threadPool.setRejectedExecutionHandler(properties.getRejectedExecutionHandler().newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }

    public static Executor geTSaskExecutor() {
        if (taskExecutor == null) {
            taskExecutor = SpringContext.get().getBean("taskExecutor", Executor.class);
        }
        return taskExecutor;
    }
}
